package com.tcoiss.common.log.service;


import com.tcoiss.common.component.api.RemoteLogService;
import com.tcoiss.common.component.api.model.*;
import com.tcoiss.common.component.servicehelper.DispatchServiceHelper;
import com.tcoiss.common.core.constant.ServiceNameConstants;
import com.tcoiss.common.core.domain.R;
import com.tcoiss.common.core.enums.ErroEnums;
import com.tcoiss.common.core.exception.CustomException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.Map;

/**
 * 异步调用日志服务
 * 
 * @author tcoiss
 */
@Service
public class AsyncLogService
{

    @Autowired
    private RemoteLogService remoteLogService;

    /**
     * 保存系统日志记录
     */
    @Async
    public void saveSysLog(OperLog sysOperLog)
    {
        remoteLogService.saveLog(sysOperLog);
    }

    @Async
    public void saveApiLog(ApiLogVo apiLog)
    {
        //根据api编码查询api配置信息
        R<ApiLogVo> result = DispatchServiceHelper.invokeBizService("tcoiss", ServiceNameConstants.WEBAPI_SERVICE,"getApiConfigByNo",apiLog);
        if(result.getCode()==200){
            remoteLogService.saveApiLog(result.getData());
        }else {
            throw new CustomException(ErroEnums.APIERRO.getCode(),new Object[]{apiLog.getApiCode()},ErroEnums.APIERRO.getInfo()+"查询api配置信息异常");
        }

    }

    @Async
    public void saveSchemeLog(SchemeLogVo schemeLog){
        //schemeLog = remoteLogService.queryWork(schemeLog);
        SchemeVO schemeVO = new SchemeVO();
        schemeVO.setExecuteNumber(schemeLog.getExecuteNumber());
        R<Map<String,Object>> result = DispatchServiceHelper.invokeBizService("tcoiss", ServiceNameConstants.DATA_SERVICE,"querySchemeWorks",schemeVO);
        if(result.getCode()==200){
            Map<String,Object> map = result.getData();
            schemeLog.setSchemeName(map.get("schemeName").toString());
            schemeLog.setWorkNum(Integer.valueOf(map.get("workNum").toString()));
        }
        remoteLogService.saveSchemeLog(schemeLog);
        schemeVO.setExecuteStatus("0");
        R result2 = DispatchServiceHelper.invokeBizService("tcoiss", ServiceNameConstants.DATA_SERVICE,"editByNumber",schemeVO);
        if(result2.getCode()!=200){
            throw new CustomException(ErroEnums.DATAERRO.getCode(),new Object[]{schemeLog.getSchemeName()},ErroEnums.DATAERRO.getInfo()+"执行结束时，更新方案状态失败");
        }
    }
}
